/**
 * Created by XianTao on 2016/11/6
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.handle.exception.configuration;

import org.lego.handle.exception.ExtraInvalidParameterException;
import org.lego.handle.exception.entity.ExceptionMessage;
import org.lego.handle.exception.service.ExceptionMessageService;
import org.lego.jpa.base.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.security.InvalidParameterException;

/**
 * 从数据库中获取异常消息
 */
@ControllerAdvice
public class DbExceptionHandler {
    @Autowired
    private ExceptionMessageService exceptionMessageService;

    @ExceptionHandler(InvalidParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultVo processInvalidParameterException(InvalidParameterException e) {
        String key = e.getMessage();
        Object[] params = new Object[]{};
        if (key.contains(ExtraInvalidParameterException.SEPARATOR_FOR_PARAMS)) {
            int tempIndex = key.lastIndexOf(ExtraInvalidParameterException.SEPARATOR_FOR_PARAMS);
            params = key.substring(0, tempIndex).split(ExtraInvalidParameterException.SEPARATOR_FOR_PARAMS);
            key = key.substring(tempIndex + 1);
        }

        return new ResultVo(findMessageFromDB(key, params));
    }

    private String findMessageFromDB(String key, Object[] params) {
        String message = "No message found by id \'" + key + "\'.";
        if (StringUtils.hasText(key)) {
            ExceptionMessage exceptionMessage = exceptionMessageService.findOne(key);
            if (exceptionMessage != null) {
                message = exceptionMessage.getMessage();
                if (!ObjectUtils.isEmpty(params)) {
                    message = String.format(message, params);
                }
            }
        }
        return message;
    }
}
